package com.limiter;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 令牌桶
 */
public class TokenBucketLimter {
    //桶的容量
    private static long capacity=10;
    //放入令牌的速率
    private static long rate=2;
    //上次令牌的时间
    private static long lastTime = System.currentTimeMillis();
    //桶中令牌的数量
    private static AtomicLong tokenNum = new AtomicLong();

    public synchronized static boolean tryAcquire(){
        //更新桶中剩余令牌
        long now = System.currentTimeMillis();
        tokenNum.addAndGet((now - lastTime)/1000*rate);
        //更新时间
        lastTime=(now - lastTime)/1000*1000;
        if(tokenNum.get()>0){
            tokenNum.decrementAndGet();
            return true;
        }else {
            return false;
        }
    }
}
